package com.wframe.project.former.dataservices.products;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import org.apache.commons.lang.StringUtils;
import org.hibernate.HibernateException;
import org.json.JSONArray;
import org.springframework.transaction.annotation.Transactional;

import com.frame.database.JBaseService;
import com.frame.database.JServiceFactory;
import com.frame.database.JdataBean;
import com.frame.database.PageResult;
import com.frame.metadata.wordbook.WordbookDao;
import com.frame.pageform.component.JsonObject;
import com.frame.util.DataBeanUtils;
import com.frame.util.SelectItem;
import com.wframe.project.former.dataservices.products.dao.ProductClassDao;
import com.wframe.project.former.dataservices.products.dao.ProductsDao;
import com.wframe.project.former.dataservices.sysman.SysmanService;
import com.wframe.project.former.dataservices.upload.UploadDao;
import com.wframe.project.former.entity.ProductPriceAttrVo;
import com.wframe.project.former.entity.ProductsAttrvalBean;
import com.wframe.project.former.entity.ProductsPricesBean;
import com.wframe.project.jnd.util.WebUtils;

/**
 * 
 * 功能:商品管理数据服务<br>
 * 参数:<br>
 * 作者:王海锋<br>
 * 时间:2017-1-13上午10:57:56<br>
 */
public class ProductService extends JBaseService<ProductsDao>{

	private int codeMaxLen=12;
	
	ProductClassDao clsDao=new ProductClassDao();
	
	public static ProductService getIntance(){
		return JServiceFactory.createJServiceProxy(ProductService.class);
    }

	/**
	 * 
	 * 功能:商品查询<br>
	 * 参数:<br>
	 * 作者:王海锋<br>
	 * 时间:2017-1-14下午11:41:52<br>
	 */
	public PageResult queryProducts(JdataBean parms,int size,int pageno) throws Exception{
		return getDao().queryProducts(parms, size, pageno);
	}
	
	public PageResult queryProductPrices(JdataBean parms,int size,int pageno) throws Exception{
		return getDao().queryProductPrices(parms, size, pageno);
	}
	
	/**
	 * 
	 * 功能:所得商品模型属性以及已记录属性值<br>
	 * 参数:<br>
	 * 作者:王海锋<br>
	 * 时间:2017-1-14下午11:14:04<br>
	 */
	public List<JdataBean> queryAllModelAttrAndVal(String classcode,String productid,Integer tag) throws Exception{
		List<JdataBean> attrlist=getDao().queryAllModelAttrAndVal(classcode,productid,tag);
		ProductClassDao classDao=new ProductClassDao();
		for(JdataBean attr:attrlist){
			String val=attr.getDefault("val", "").toString();
			List<JdataBean> itemlist=classDao.queryModelAttrItem(attr.getString("id"));
			if(attr.getInt("type")==2 || attr.getInt("type")==3){
				String[] vals=val.split(",");
				for(String v:vals){
					for(JdataBean item:itemlist){
						if(item.getString("code").equals(v)){
							item.put("selected", "true");
							break;
						}
					}
				}
			}
			attr.put("itemlist", itemlist);
		}
		return attrlist;
	}
	
	/**
	 * 
	 * 功能:获得商品所属分类<br>
	 * 参数:<br>
	 * 作者:王海锋<br>
	 * 时间:2017-1-15下午03:51:50<br>
	 */
	public JdataBean getProductClass(String productid) throws Exception{
		return getDao().getProductClass(productid);
	}
	
	/**
	 * 
	 * 功能:保存商品信息<br>
	 * 参数:<br>
	 * 作者:王海锋<br>
	 * 时间:2017-1-17上午10:56:53<br>
	 * @throws Exception 
	 * @throws HibernateException 
	 */
	
	public String saveProduct(JdataBean basedata,JdataBean attrdata) throws HibernateException, Exception{
		String productid="";
		String classid=basedata.getString("classid");
		String[] photos=basedata.get("photos")==null?null:(String[])basedata.get("photos");
		basedata.remove("photos");
		basedata.remove("classid");
		UploadDao updao=new UploadDao();
		ProductClassDao clsdao=new ProductClassDao();
		List<ProductsAttrvalBean> attrList=(List<ProductsAttrvalBean>)attrdata.get("attrList");
		String attrjson=attrToJson(attrList);
		basedata.put("attrvals", attrjson);
		if(StringUtils.isNotBlank(basedata.getString("id"))){
			//修改
			productid=basedata.getString("id");
			
			if(photos!=null){
				String photodataid=updao.createDataid();
				updao.setPhotoDataId(photodataid, photos);//将多图片归属同一组
				basedata.put("photodataid", photodataid);
			}
			basedata.put("edittime", new Date());
			Map key=new HashMap();
			key.put("id", productid);
			getDao().update(basedata.getDataMap(),key);
		}else{
			//新增
			if(photos!=null){
				String photodataid=updao.createDataid();
				updao.setPhotoDataId(photodataid, photos);//将多图片归属同一组
				basedata.put("photodataid", photodataid);
			}
			basedata.put("createtime", new Date());
			productid=getDao().getSession().saveReturnKey("wb_products", basedata.getDataMap());
		}
		JdataBean codebean=clsdao.getBean(classid);
		String clscode="";
		if(codebean!=null)clscode=codebean.getString("code");
		getDao().saveProductAndClass(classid,clscode, productid);//保存商品分类
		getDao().saveProductsAttrval(new Integer(productid),attrList);//保存商品属性值
		List<ProductsPricesBean> priceList=(List<ProductsPricesBean>)attrdata.get("priceList");
		List<JdataBean> pricebeanList=new ArrayList<JdataBean>();
		for(ProductsPricesBean pbean:priceList){
			if(pbean.getPhotodataids()!=null){
				String photodataid=updao.createDataid();
				updao.setPhotoDataId(photodataid, pbean.getPhotodataids());
				pbean.setPhotodataid(photodataid);
			}
			JdataBean pdata=DataBeanUtils.beanToMap(pbean);
			pdata.remove("photodataids");
			pricebeanList.add(pdata);
		}
		getDao().saveProductsPrices(new Integer(productid), pricebeanList);
		return productid;
	}
	
	public List<JdataBean> queryProductsPrices(String productid) throws Exception{
		List<JdataBean> list=getDao().queryProductsPrices(productid);
		UploadDao updao=new UploadDao();
		for(JdataBean data:list){
			String attrdesc="";
			if("0".equals(data.getString("attrcodes"))){
				attrdesc=data.getString("name");
			}else{
				List<ProductPriceAttrVo> volist=WebUtils.strToPriceAttrVo(data.getString("attrcodes"));
				attrdesc+=getAttrdesc(volist);
			}
			data.put("attrdesc", attrdesc);
			
			if(StringUtils.isNotBlank(data.getString("photodataid")))
				data.put("photos", updao.queryPhotos(data.getString("photodataid")));
		}
		return list;
	}
	
	public String getAttrdesc(List<ProductPriceAttrVo> volist) throws Exception{
		String attrdesc="";
		for(ProductPriceAttrVo vo:volist){//将销售属性信息进行字符拼接
			JdataBean attrbean=clsDao.getModelAttr(vo.getAttrid());//属性名称
			if(!"".equals(attrdesc))attrdesc+="、";
			attrdesc+=attrbean.getString("name")+":[";
			List<JdataBean> items=clsDao.queryModelAttrItemByCodes(vo.getItemcodes());//属性值
			for(int i=0;i<items.size();i++){if(i!=0)attrdesc+=",";attrdesc+=items.get(i).getString("text");}
			attrdesc+="]";
		}
		return attrdesc;
	}
	
	public void delProduct(String id) throws Exception{
		getDao().delProduct(id);
	}
	
	public void shelves(String[] proids) throws Exception{
		getDao().shelves(proids);
	}
	
	public void offshelf(String[] proids) throws Exception{
		getDao().offshelf(proids);
	}
	
	/**
	 * 商品库存查询
	 * @param parms
	 * @param size
	 * @param pageno
	 * @return
	 * @throws Exception
	 */
	public PageResult queryStockList(JdataBean parms, int size, int pageno) throws Exception {
		return getDao().queryStockList(parms, size, pageno);
	}
	
	public JdataBean getProductsPrices(String id) throws Exception{
		return getDao().getProductsPrices(id);
	}
	public void updateProductsPrices(String id,JdataBean bean) throws Exception{
		getDao().updateProductsPrices(id,bean);
	}
	
	/**
	 * 将商品属性转json字符
	 * @param attrs
	 * @return
	 * @throws Exception
	 */
	public String attrToJson(List<ProductsAttrvalBean> attrs) throws Exception{
		ProductClassDao clasDao=new ProductClassDao();
		for(ProductsAttrvalBean attrbean:attrs){
			JdataBean mbean=clasDao.getModelAttr(attrbean.getAttrid().toString());
			attrbean.setAttrcode(mbean.getString("code"));
			List<String> attrcodes=new ArrayList<String>();
			String[] vals=attrbean.getVal().split(",");
			for(String valcode:vals)attrcodes.add(valcode);
			List<JdataBean> items=clasDao.queryModelAttrItemByCodes(attrcodes);
			String txt="";
			for(JdataBean item:items){
				if(!"".equals(txt))txt+=",";
				txt+=item.getString("text");
			}
			attrbean.setValtxt(txt);
		}
		return new JsonObject().objToJson(attrs);
	}
	
	public void addControlsales(String productid,JSONArray sales,String userids) throws Exception{
		getDao().delControlsalesAll( productid);
		String[] uids=null;if(StringUtils.isNotBlank(userids))uids=userids.split(",");
		int iscontrol=0;
		if(uids!=null && uids.length>0)iscontrol=1;
		if(sales!=null && sales.length()>0)iscontrol=1;
		getDao().updatecontrol(productid, iscontrol);//标记控销状态
		if(sales!=null){
			for(int i=0;i<sales.length();i++){
				JdataBean bean=new JdataBean();
				bean.put("productid", productid);
				bean.put("type", sales.getJSONObject(i).getString("type"));
				bean.put("val", sales.getJSONObject(i).getString("val"));
				bean.put("text", sales.getJSONObject(i).getString("text"));
				getDao().addControlsales(bean);
			}
		}
		if(uids!=null){
			for(String uid:uids){
				JdataBean bean=new JdataBean();
				bean.put("productid", productid);
				bean.put("type", 4);
				bean.put("val",uid);
				getDao().addControlsales(bean);
			}
		}
		
	}
	public List<JdataBean> queryControlsales(String productid) throws Exception{
		return getDao().queryControlsales(productid);
	}
	public List<JdataBean> queryControlUsers(String productid) throws Exception{
		return getDao().queryControlUsers(productid);
	}
	public List<JdataBean> queryPricegrade(String productid) throws Exception{
		List<SelectItem> items=new WordbookDao().queryItem("PriceGrade");
		List<JdataBean> prices=getDao().queryPricegrade(productid);
		List<JdataBean> list=new ArrayList<JdataBean>();
		for(SelectItem item:items){
			JdataBean bean=new JdataBean();
			bean.put("value", item.getValue());
			bean.put("text", item.getText());
			for(JdataBean price:prices){
				if(price.getString("grade").equals(item.getValue())){
					bean.put("price", price.get("price"));
					break;
				}
			}
			list.add(bean);
		}
		return list;
	}
	public void savePricegrade(String productid,JSONArray prics) throws HibernateException, Exception{
		getDao().delPricegradeAll( productid);
		if(prics!=null){
			for(int i=0;i<prics.length();i++){
				JdataBean bean=new JdataBean();
				bean.put("productid", productid);
				bean.put("grade", prics.getJSONObject(i).getString("grade"));
				bean.put("price", prics.getJSONObject(i).getString("price"));
				getDao().addPricegrade(bean);
			}
		}
	}
	
	public PageResult queryHotProducts(JdataBean parms, int size, int pageno) throws Exception{
		PageResult pr=getDao().queryHotProducts(parms, size, pageno);
		List<JdataBean> productlist=pr.getList();
		ProductClassDao clsDao=new ProductClassDao();
		for(JdataBean product:productlist){
			String photo=product.get("photoview")==null?"":product.get("photoview").toString();
			if(StringUtils.isBlank(photo))photo=product.get("product_photoview")==null?"":product.get("product_photoview").toString();
			product.put("photo", photo);
			product.put("clsName", clsDao.getProductClassName(product.getString("productid")));
			product.put("fullname", product.getString("productname")+" "+product.getDefault("name","").toString());
		}
		return pr;
	}
	
	public void addHotProducts(String[] priceids) throws HibernateException, Exception{
		getDao().delHotProductAll();
		getDao().saveHotProducts(priceids);
	}
	public void delHotProduct(String[] priceids) throws HibernateException, Exception{
		if(priceids!=null)getDao().delHotProduct(priceids);
	}
	public void hotProductStatus(String[] priceids,int status) throws HibernateException, Exception{
		if(priceids!=null)getDao().hotProductStatus(priceids,status);
	}
	
	
	/**
	 * 
	 * 功能:系统生成商品编码<br>
	 * 参数:classid商品分类id<br>
	 * 作者:王海锋<br>
	 * 时间:2017-1-6上午01:58:58<br>
	 */
	public String createProductCode(String classid){
		long diff=new Date().getTime()-WebUtils.basecodetime;
		diff=diff/1000;
		long timecode=diff/(60*60);//小时差
		String code=classid+String.valueOf(timecode);
		Random random=new Random();
		int len=code.length();
		int m=codeMaxLen-len;
		for(int i=0;i<m;i++)
			code+=random.nextInt(9);
		return code;
	}
	
}
